from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel
from PyQt5.QtCore import Qt
from steps_widget import StepsWidget

class DeviceDetailWidget(QWidget):
    def __init__(self, device_name, back_callback, parent=None):
        super().__init__(parent)
        self.device_name = device_name
        self.back_callback = back_callback
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout(self)

        # 创建一个水平布局用于放置返回按钮和设备信息
        top_layout = QHBoxLayout()

        # 返回按钮
        back_button = QPushButton("返回", self)
        back_button.setFixedWidth(100)  # 设置固定宽度，例如100像素
        back_button.clicked.connect(self.back_callback)  # 绑定返回操作
        top_layout.addWidget(back_button)

        # 设备信息
        info_label = QLabel(f'正在显示设备: {self.device_name}', self)
        info_label.setAlignment(Qt.AlignLeft)  # 左对齐
        top_layout.addWidget(info_label)

        layout.addLayout(top_layout)  # 将水平布局添加到主布局中

        # 步骤条
        steps = ["数据上报", "指令下发", "FOTA升级", "SOTA升级"]
        descriptions = ["数据上报", "指令下发", "FOTA升级", "SOTA升级"]
        self.steps_widget = StepsWidget(steps, descriptions)
        layout.addWidget(self.steps_widget)
        # 连接步骤点击信号
        self.steps_widget.stepClicked.connect(self.showStepDetail)
        # 设置布局的对齐
        layout.setAlignment(Qt.AlignTop | Qt.AlignLeft)

        # 详细信息标签已由StepsWidget内部的detail_area替代
        # 不再需要单独的detail_label

    def showStepDetail(self, step_index):
        """显示所点击步骤的测试详情"""
        # 这个方法现在由StepsWidget内部处理，这里只需要触发显示即可
        pass

    def updateSteps(self, test_device_name, step_index, status):
        """更新步骤的状态"""
        if test_device_name == self.device_name:
            print(f"更新步骤 {step_index} 的状态为 {status}")
            # 直接使用传入的状态字符串
            self.steps_widget.updateStepStatus(step_index, status)

            # 自动展开当前进行中的步骤详情
            if status == "in_progress":
                self.steps_widget.showStepDetail(step_index)
    
    def update_step_detail(self, step_index, detail_text):
        """更新步骤的详细信息
        
        Args:
            step_index (int): 步骤索引
            detail_text (str): 详情文本
        """
        try:
            if hasattr(self, 'steps_widget'):
                # 将详情文本添加到步骤详情中
                self.steps_widget.addStepDetail(step_index, detail_text)
                
                # 如果当前正在显示该步骤的详情，则刷新显示
                if self.steps_widget.selected_step == step_index:
                    self.steps_widget.showStepDetail(step_index)
        except Exception as e:
            print(f"更新步骤 {step_index} 的详情时出错: {e}")